package coreservlets;

import java.util.concurrent.*;

/** The main class implementing Runnable (variation 2 of 3).
 *  <p>
 *  From <a href="http://courses.coreservlets.com/Course-Materials/">the
 *  coreservlets.com tutorials on JSF 2, PrimeFaces, Ajax, jQuery, GWT, Android,
 *  Spring, Hibernate, JPA, RESTful Web Services, Hadoop, 
 *  servlets, JSP, and Java 7 and Java 8 programming</a>.
 */

public class App2 extends SomeClass implements Runnable {
  private final int loopLimit;

  public App2(int loopLimit) {
    this.loopLimit = loopLimit;
    ExecutorService taskList = 
      Executors.newFixedThreadPool(100);
    taskList.execute(this);
    taskList.execute(this);
    taskList.execute(this);
    taskList.shutdown();
  }
  
  private void pause(double seconds) {
    try {
      Thread.sleep(Math.round(1000.0 * seconds));
    } catch (InterruptedException ie) { }
  }

  // This run method can easily access methods and instance variables in the
  // main class, since it is INSIDE the main class. If you start multiple threads
  // and "run" modifies instance variables, you have to worry about race conditions.
  // It is very difficult to pass arguments to run, so each thread does almost
  // the same thing. If you want to pass arguments, use Runnable inner classes instead.
  public void run() {
    for(int i=0; i<loopLimit; i++) {
      String threadName = Thread.currentThread().getName();
      System.out.printf("%s: %s%n", threadName, i);
      pause(Math.random()); // Sleep for up to 1 second
    }
  }
}